require 'open-uri'
require 'cgi'
require 'rubygems' rescue nil
require 'nokogiri'


class SiteProxyController < ApplicationController
  
  def proxy
    url = params[:url]
    base_url = params[:base_url]
    #doc = Hpricot(open(url))
    doc = Nokogiri::HTML(open(url))
    #get the start of domain
    domain = URI.parse(url).host
    proxy_val = site_proxy_path
    
    doc.css("link").each do |link|
      link.attributes["href"].value = base_url+link.attributes["href"].value if link.attributes["href"]
    end
    
    doc.css("a").each do |link|
      link.attributes["href"].value = base_url+link.attributes["href"].value if link.attributes["href"]
    end
    doc.css("img").each do |link|
      link.attributes["src"].value = base_url+link.attributes["src"].value if link.attributes["src"]
    end
    
    doc.css("a").each do |link|
      if link.attributes["href"].value and link.attributes["href"].value.match(/#{domain}/)
        link.attributes["href"].value = "#{proxy_val}/?base_url=#{base_url}&url=#{CGI.escape link.attributes["href"].value}" if link.attributes["href"]
      else 
        if link.attributes["target"]
          link.attributes["target"].value = "_blank"
        else
          link.set_attribute("target","_blank")
        end
      end
      
      
    end
    render :partial=>"html_instrumentation", :locals=>{:html=>doc.to_s}
    
  end
end
